﻿using UnityEngine;

using System.IO;
using System.Linq;
using Puerts;

#if UNITY_2020_3_OR_NEWER
using UnityEditor.AssetImporters;
#else 
using  UnityEditor.Experimental.AssetImporters;
#endif
[ScriptedImporter(1, ".ts")]
public class TypeScriptsImporter : ScriptedImporter{
	public override void OnImportAsset(AssetImportContext ctx)
	{
		string path = ctx.assetPath;
		if (!(path.Contains("TypeScript") || path.Contains("/Puerts/")))
			return;
		//script text
		string module = path.Substring(path.IndexOf("/TypeScript/")+"/TypeScript/".Length);
		module = module.Split('.')[0];
		var script = TypeScript.CreateFromFile(module);

		script.name = module;
		//script text
		string jsFile = Path.GetFullPath(JsLoader.PathJs + module + ".js");
		if (File.Exists(jsFile))
			script.m_compiled = File.GetLastWriteTime(path) < File.GetLastWriteTime(jsFile);
		//script asset
#if UNITY_2017_3_OR_NEWER
		Texture2D t = TypeScriptCreator.ThambNail();
		ctx.AddObjectToAsset ("script", script,t);
		ctx.SetMainObject (script);
#else
		ctx.SetMainAsset("script", script);
#endif
	} 
}